package com.candy.shoporder.controller;

import com.candy.entity.Order;
import com.candy.shoporder.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@RestController
@RequestMapping("/orders")
@RefreshScope
public class OrderController {
    @Autowired
    OrderService orderService;
    @Autowired
    RestTemplate restTemplate;
    @Autowired
    DiscoveryClient discoveryClient;

    @Value("${athor}")
    String athor;

    @Value("${spring.datasource.username}")
    String username;


    @RequestMapping("/addOrder")
    public String addOrder(){
        Order order=new Order();
        order.setUserId(1);
        order.setPrice(61.5);
        order.setProductId(1);
        order.setAmount(61.5);
        order.setNumber(1);
        order.setUsername("candy");
        order.setProductName("Java从入门到精通");
        orderService.addOrder(order);
//        可以通过discoveryClient获取服务的示例
//        服务指定服务product服务的实例集合
        List<ServiceInstance> instances=discoveryClient.getInstances("shop-product");
//        因为服务只有一个，所在通过索引0获取示例
        ServiceInstance instance=instances.get(0);
//        获取服务实例对应的信息，如：host\port
        String productHost=instance.getHost();
        int productPort=instance.getPort();
        System.out.println("prodduct服务对应的host:"+productHost);
        System.out.println("prodduct服务对应的port:"+productPort);


        System.out.println("athor:"+athor);

        System.out.println("datasource.username:"+username);
//        调用库存服务(默认使用restTemplate进行调用服务时进行使用
//        String productMethodResponse=restTemplate.getForObject("http://localhost:8082/editProduct",String.class);
//        添加负载均衡配置后，可以直接通过服务名进行调用服务实例
        String productMethodResponse=restTemplate.getForObject("http://shop-product/product/editProduct",String.class);
        return "下单成功!"+productMethodResponse;
    }
}
